/*
 * @Descripttion : Tooltip 文字提示
 * @Author       : QianFox Team
 * @Date         : 2022-05-07 16:15:57
 * @LastEditors  : QianFox Team
 * @LastEditTime : 2022-08-18 09:09:22
 */

import { _typeOf } from './common/utils';
import { Tip } from './tip';

function Tooltip() {
    Tip.call(this);
    this.CLASS_NAME = 'foxui-tooltip';
    this.EFFECTLIST = ['dark', 'light'];
    this.effect = 'dark';

    this.timer = null;
}

Object.setPrototypeOf(Tooltip.prototype, Tip.prototype);

Tooltip.prototype._init = function ({ el, content, placement, className, width, effect }) {
    // 保存数据及配置
    this.el = el;
    this.content = content || '';
    _typeOf(placement) === 'array' && placement.length > 0 && (this.placement = placement);
    this.className = className || '';
    this.width = width || 'auto';
    this.effect = this.EFFECTLIST.indexOf(effect) !== -1 ? effect : 'dark';

    // 绑定初始化事件
    this._bindSetPosition();
    this._bindTriggerEvent();
};

Tooltip.prototype._appendHtml = function () {
    // 追加 confirmtip 内容
    $('body').append(this._html());
};

Tooltip.prototype._bindTriggerEvent = function () {
    let that = this;

    $(document).on('mouseover', this.el, function () {
        // 清除定时器
        clearTimeout(that.timer);
        that.timer = null;

        if ($(`#${that.foxId}`).length < 1) {
            that._appendHtml();
        }

        that._show();
    });

    $(document).on('mouseout', this.el, function () {
        // 设置关闭定时器
        that.timer = setTimeout(() => {
            that._close();
        }, 250);
    });

    $(document).on('mouseenter', `#${this.foxId}`, function () {
        // 清除定时器
        clearTimeout(that.timer);
        that.timer = null;
    });

    $(document).on('mouseleave', `#${this.foxId}`, function () {
        that.timer = setTimeout(() => {
            that._close();
        }, 250);
    });
};

/**
 * @description: 实例初始化组件
 * @param {*} el                    触发按钮节点
 * @param {*} content               主体内容
 * @param {*} placement             三角形位置
 * @param {*} className             弹框最外层类名
 * @param {*} width                 弹框宽度
 * @param {*} effect                类型：1、dark； 2、light;
 * @return {*}
 * @Date: 2022-05-07 20:26:40
 */
function tooltip({ el, content, placement, className, width, effect }) {
    $(el).each(function () {
        const hasFoxid = $(this).attr('data-foxid') ? true : false;

        if (!hasFoxid) {
            let tooltip = new Tooltip(),
                foxid = tooltip.foxId;

            $(this).attr('data-foxid', foxid);
            tooltip._init({ el: `${el}[data-foxid=${foxid}]`, content, placement, className, width, effect });

            return tooltip;
        }
    });
}

export { tooltip };
